<?php
/**
 * 推荐人设置
 */

namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Lang;
/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Inviter extends AdminControl
{
public function initialize()
{
    parent::initialize(); // TODO: Change the autogenerated stub
    Lang::load(base_path().'admin/lang/'.config('lang.default_lang').'/inviter.lang.php');
}

    /**
     * 基本设置
     */
    public function setting(){
        $config_model = model('config');
        if (request()->isPost()){
            $upload_file = BASE_UPLOAD_PATH . DIRECTORY_SEPARATOR . ATTACH_COMMON;
            if (!empty($_FILES['inviter_back']['name'])) {
                $file = request()->file('inviter_back');

                
                $file_config = array(
                    'disks' => array(
                        'local' => array(
                            'root' => $upload_file
                        )
                    )
                );
                config($file_config, 'filesystem');
                try {
                    validate(['image' => 'fileSize:' . ALLOW_IMG_SIZE . '|fileExt:' . ALLOW_IMG_EXT])
                            ->check(['image' => $file]);
                    $file_name = \think\facade\Filesystem::putFileAs('', $file, 'inviter_back.png');
                    $upload['inviter_back'] = $file_name;
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            if (!empty($upload['inviter_back'])) {
                $update_array['inviter_back'] = $upload['inviter_back'];
            }
            $update_array['inviter_ratio_1']=floatval(input('post.inviter_ratio_1'));
            $update_array['inviter_ratio_2']=floatval(input('post.inviter_ratio_2'));
            $update_array['inviter_ratio_3']=floatval(input('post.inviter_ratio_3'));
            
            $update_array['inviter_open']=intval(input('post.inviter_open'));
            $update_array['inviter_level']=intval(input('post.inviter_level'));
            $update_array['inviter_show']=floatval(input('post.inviter_show'));
            $update_array['inviter_return']=floatval(input('post.inviter_return'));
            $update_array['inviter_view']=floatval(input('post.inviter_view'));
            $update_array['inviter_condition']=floatval(input('post.inviter_condition'));
            $update_array['inviter_condition_amount']=floatval(input('post.inviter_condition_amount'));
            
            
            $result = $config_model->editConfig($update_array);
            if ($result) {
                $this->log(lang('ds_inviter_set'),1);
                $this->success(lang('ds_common_op_succ'), 'Inviter/setting');
            }else{
                $this->log(lang('ds_inviter_set'),0);
            }
        } else {
            $list_setting = rkcache('config', true);
            View::assign('list_setting', $list_setting);
            $this->setAdminCurItem('index');
            return View::fetch('index');
        }
    }
    
    public function goods(){
        $goods_model=model('goods');
        $condition = array();
        $condition[]=array('inviter_open','=',1);
        if ((input('param.goods_name'))) {
            $condition[]=array('goods_name','like', '%' . input('param.goods_name') . '%');
        }
  
        $goods_list = $goods_model->getGoodsCommonList($condition, '*', 10);
        View::assign('goods_list', $goods_list);
        View::assign('show_page', $goods_model->page_info->render());
        
        $this->setAdminCurItem('goods');
        return View::fetch('goods');
    }
    
    public function order(){
        $search_field_value = input('param.search_field_value');
        $search_field_name = input('param.search_field_name');
        $condition = array();
        if ($search_field_value != '') {
            switch ($search_field_name) {
                case 'orderinviter_member_name':
                    $condition[] = array('orderinviter_member_name','=',$search_field_value);
                    break;
                case 'orderinviter_order_sn':
                    $condition[] = array('orderinviter_order_sn','=',$search_field_value);
                    break;
                case 'orderinviter_store_name':
                    $condition[] = array('orderinviter_store_name','=',$search_field_value);
                    break;
            }
        }
  
        $orderinviter_list=Db::name('orderinviter')->where($condition)->order('orderinviter_addtime desc')->paginate(['list_rows'=>10,'query' => request()->param()],false);
        View::assign('orderinviter_list', $orderinviter_list->items());
        View::assign('show_page', $orderinviter_list->render());
        View::assign('search_field_name', trim($search_field_name));
        View::assign('search_field_value', trim($search_field_value));
        View::assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('order');
        return View::fetch();
    }
    
    public function member(){
        $inviter_model=model('inviter');
        $search_field_value = input('search_field_value');
        $search_field_name = input('search_field_name');
        $condition = array();
        if ($search_field_value != '') {
            switch ($search_field_name) {
                case 'member_name':
                    $condition[]=array('member_name','like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_email':
                    $condition[]=array('member_email','like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_mobile':
                    $condition[]=array('member_mobile','like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_truename':
                    $condition[]=array('member_truename','like', '%' . trim($search_field_value) . '%');
                    break;
            }
        }
  
        $member_list = $inviter_model->getInviterList($condition, 10,'','i.*,m.inviter_id as inviter_parent_id,m.member_id,m.member_ww,m.member_qq,m.member_addtime,m.member_name,m.member_avatar,m.member_email,m.member_mobile,m.member_truename');
        $inviterclass_model=model('inviterclass');
        foreach($member_list as $key => $item){
            $member_list[$key]['inviter_parent_name']='';
            $member_list[$key]['inviter_class']='';
            $member_list[$key]['inviter_class']=$inviterclass_model->getInviterclass($item['inviter_total_amount']);
            if($item['inviter_parent_id']){
                $member_list[$key]['inviter_parent_name'] = Db::name('member')->where('member_id='.$item['inviter_parent_id'])->value('member_name');
            }
        }
        View::assign('member_list', $member_list);
        View::assign('show_page', $inviter_model->page_info->render());
        View::assign('search_field_name', trim($search_field_name));
        View::assign('search_field_value', trim($search_field_value));
        View::assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('member');
        return View::fetch('member');
    }
    public function memberclass(){
        $memberclass_list=Db::name('inviterclass')->order('inviterclass_amount asc')->select()->toArray();
        View::assign('memberclass_list',$memberclass_list);
        $this->setAdminCurItem('memberclass');
        return View::fetch('memberclass');
    }
    
    public function member_adjust(){
        $member_id=intval(input('param.member_id'));
        if(!$member_id){
            $this->error(lang('param_error'));
        }
        $inviter_model=model('inviter');
        $inviter_info=$inviter_model->getInviterInfo(array('m.member_id'=>$member_id),'m.member_id,m.inviter_id as inviter_parent_id,i.inviter_1_quantity,i.inviter_2_quantity,i.inviter_3_quantity');
        if(!$inviter_info){
            $this->error(lang('inviter_member_empty'));
        }
        if (request()->isPost()) {
            $member_name=trim(input('param.member_name'));
            if($member_name){
                $inviter=$inviter_model->getInviterInfo(array('m.member_name'=>$member_name),'m.member_id');
                $inviter_id=$inviter['member_id'];
                if(!$inviter_id){
                    $this->error(lang('inviter_member_empty'));
                }
                //上级不能是自己
                if($inviter_id==$member_id){
                    $this->error(lang('inviter_parent_error'));
                }
                //上级不能是自己下级中（3级内）的成员
                if(Db::name('member')->where('inviter_id='.$member_id.' AND member_id='.$inviter_id)->value('member_id')){
                    $this->error(lang('inviter_parent_error2'));
                }
                $subQuery=Db::name('member')->field('member_id')->where('inviter_id='.$member_id)->buildSql();
                
                if(Db::name('member')->where('member_id='.$inviter_id.' AND inviter_id IN'.$subQuery)->value('member_id')){
                    $this->error(lang('inviter_parent_error2'));
                }
                $subQuery=Db::name('member')->field('member_id')->where('inviter_id IN'.$subQuery)->buildSql();
                if(Db::name('member')->where('member_id='.$inviter_id.' AND inviter_id IN'.$subQuery)->value('member_id')){
                    $this->error(lang('inviter_parent_error2'));
                }
            }else{
                $inviter_id=0;
            }
            Db::name('member')->where('member_id='.$member_id)->update(array(
                'inviter_id'=>$inviter_id
            ));
            //给旧的父级减去下线成员
            if($inviter_info['inviter_parent_id']){
                Db::name('inviter')->where('inviter_id='.$inviter_info['inviter_parent_id'].' AND inviter_1_quantity>=1')->dec('inviter_1_quantity')->update();
                Db::name('inviter')->where('inviter_id='.$inviter_info['inviter_parent_id'].' AND inviter_2_quantity>='.$inviter_info['inviter_1_quantity'])->dec('inviter_2_quantity',$inviter_info['inviter_1_quantity'])->update();
                Db::name('inviter')->where('inviter_id='.$inviter_info['inviter_parent_id'].' AND inviter_3_quantity>='.$inviter_info['inviter_2_quantity'])->dec('inviter_3_quantity',$inviter_info['inviter_2_quantity'])->update();
                //父级的父级
                $temp=$inviter_model->getInviterInfo(array('m.member_id'=>$inviter_info['inviter_parent_id']),'m.inviter_id as inviter_parent_id');
                if($temp['inviter_parent_id']){
                    Db::name('inviter')->where('inviter_id='.$temp['inviter_parent_id'].' AND inviter_2_quantity>=1')->dec('inviter_2_quantity')->update();
                    Db::name('inviter')->where('inviter_id='.$temp['inviter_parent_id'].' AND inviter_3_quantity>='.$inviter_info['inviter_1_quantity'])->dec('inviter_3_quantity',$inviter_info['inviter_1_quantity'])->update();
                    //父级的父级的父级
                    $temp=$inviter_model->getInviterInfo(array('m.member_id'=>$temp['inviter_parent_id']),'m.inviter_id as inviter_parent_id');
                    if($temp['inviter_parent_id']){
                        Db::name('inviter')->where('inviter_id='.$temp['inviter_parent_id'].' AND inviter_3_quantity>=1')->dec('inviter_3_quantity')->update();
                    }
                }
            }
            //给新的父级增加下线成员
            if($inviter_id){
                Db::name('inviter')->where('inviter_id='.$inviter_id)->inc('inviter_1_quantity')->update();
                Db::name('inviter')->where('inviter_id='.$inviter_id)->inc('inviter_2_quantity',$inviter_info['inviter_1_quantity'])->update();
                Db::name('inviter')->where('inviter_id='.$inviter_id)->inc('inviter_3_quantity',$inviter_info['inviter_2_quantity'])->update();
                //父级的父级
                $temp=$inviter_model->getInviterInfo(array('m.member_id'=>$inviter_id),'m.inviter_id as inviter_parent_id');
                if($temp['inviter_parent_id']){
                    Db::name('inviter')->where('inviter_id='.$temp['inviter_parent_id'])->inc('inviter_2_quantity')->update();
                    Db::name('inviter')->where('inviter_id='.$temp['inviter_parent_id'])->inc('inviter_3_quantity',$inviter_info['inviter_1_quantity'])->update();
                    //父级的父级的父级
                    $temp=$inviter_model->getInviterInfo(array('m.member_id'=>$temp['inviter_parent_id']),'m.inviter_id as inviter_parent_id');
                    if($temp['inviter_parent_id']){
                        Db::name('inviter')->where('inviter_id='.$temp['inviter_parent_id'])->inc('inviter_3_quantity')->update();
                    }
                }
            }
            $this->log(lang('adjust_superior') .  '[ID:' . $member_id . ']', 1);
            dsLayerOpenSuccess(lang('ds_common_op_succ'));
        }else{
            return View::fetch();
        }
    }
    
    /**
     * 添加标签
     */
    public function memberclass_add(){
        if (request()->isPost()) {
            $data=array(
                'inviterclass_name'=>trim(input('post.inviterclass_name')),
                'inviterclass_amount'=>abs(floatval(input('post.inviterclass_amount'))),
            );
            if(!$data['inviterclass_name']){
                $this->error(lang('param_error'));
            }
            Db::name('inviterclass')->insert($data);
            dsLayerOpenSuccess(lang('ds_common_op_succ'));
        }else{
            return View::fetch('memberclass_form');
        }
    }

    /**
     * 编辑标签
     */
    public function memberclass_edit()
    {
        $id=intval(input('param.id'));
        if(!$id){
            $this->error(lang('param_error'));
        }
        $inviterclass_info=Db::name('inviterclass')->where('inviterclass_id',$id)->find();
        if(!$inviterclass_info){
            $this->error(lang('inviterclass_empty'));
        }
        // 实例化模型
        if (request()->isPost()) {
            $data=array(
                'inviterclass_name'=>trim(input('post.inviterclass_name')),
                'inviterclass_amount'=>abs(floatval(input('post.inviterclass_amount'))),
            );
            if(!$data['inviterclass_name']){
                $this->error(lang('param_error'));
            }
            Db::name('inviterclass')->where('inviterclass_id',$id)->update($data);
            dsLayerOpenSuccess(lang('ds_common_op_succ'));
        }  else {

            View::assign('inviterclass_info', $inviterclass_info);
            return View::fetch('memberclass_form');
        }
    }

    /**
     * 删除标签
     */
    public function memberclass_del()
    {
        $inviterclass_id = input('param.id');
        $inviterclass_id_array = ds_delete_param($inviterclass_id);
        if ($inviterclass_id_array == FALSE) {
            ds_json_encode('10001', lang('param_error'));
        }
 
        $result=Db::name('inviterclass')->where(array(array('inviterclass_id','in',$inviterclass_id_array)))->delete();
        if ($result) {
            ds_json_encode('10000', lang('ds_common_del_succ'));
        }
        else {
            ds_json_encode('10001', lang('ds_common_del_fail'));
        }
    }

    
    
    public function memberstate(){
        $member_id=input('param.member_id');
        $member_id_array = ds_delete_param($member_id);
        $member_state=input('param.member_state');
        if(!$member_id_array || !in_array($member_state, array(1,2))){
            ds_json_encode('10001', lang('param_error'));
        }
        $inviter_model=model('inviter');
        $inviter_info=$inviter_model->getInviterInfo(array(array('i.inviter_id','in',$member_id_array)));
        if(!$inviter_info){
            ds_json_encode('10001', lang('inviter_member_empty'));
        }
        $inviter_model->editInviter(array(array('inviter_id','in',$member_id_array)),array('inviter_state'=>$member_state));
        $this->log(($member_state==1?lang('ds_enable'):lang('ds_disable')) .  '[ID:' . implode(',', $member_id_array) . ']', 1);
        ds_json_encode('10000', ($member_state==1?lang('ds_enable'):lang('ds_disable')).lang('ds_succ'));
    }

    public function memberinfo(){
        $member_id=input('param.member_id');
        if(!$member_id){
            ds_json_encode('10001', lang('param_error'));
        }
        $inviter_model=model('inviter');
        $inviter_info=$inviter_model->getInviterInfo(array('i.inviter_id'=>$member_id),'i.*,m.inviter_id as inviter_parent_id,m.member_id,m.member_ww,m.member_qq,m.member_addtime,m.member_name,m.member_avatar,m.member_email,m.member_mobile,m.member_truename');
        if(!$inviter_info){
            ds_json_encode('10001', lang('inviter_member_empty'));
        }
        $inviter_info['inviter_parent_name']='';
        if($inviter_info['inviter_parent_id']){
            $inviter_info['inviter_parent_name']= Db::name('member')->where('member_id='.$inviter_info['inviter_parent_id'])->value('member_name');
        }
        $inviterclass_model=model('inviterclass');
        $inviter_info['inviter_class']=$inviterclass_model->getInviterclass($inviter_info['inviter_total_amount']);
        View::assign('inviter_info',$inviter_info);
        $this->setAdminCurItem('member');
        return View::fetch('memberinfo');
    }
    
    public function memberlist(){
        $member_id=intval(input('param.member_id'));
        $type=input('param.type');
        if(!$member_id || !in_array($type, array(1,2,3))){
            return;
        }
        $inviter_model=model('inviter');
        if($type==1){
            $res=Db::name('member')->alias('m')->join('inviter i', 'i.inviter_id=m.member_id','LEFT')->field('i.*,m.inviter_id as inviter_parent_id,m.member_id,m.member_ww,m.member_qq,m.member_addtime,m.member_name,m.member_avatar,m.member_email,m.member_mobile,m.member_truename')->where('m.inviter_id='.$member_id)->order('inviter_applytime desc')->paginate(['list_rows'=>10,'query' => request()->param()],false);
            $page_info=$res;
            $member_list=$res->items();
        }elseif($type==2){
    
            $subQuery=Db::name('member')->alias('m')->join('inviter i', 'i.inviter_id=m.member_id','LEFT')->field('m.member_id')->where('m.inviter_id='.$member_id)->order('inviter_applytime desc')->buildSql();
            $res=Db::name('member')->alias('m')->join('inviter i', 'i.inviter_id=m.member_id','LEFT')->field('i.*,m.inviter_id as inviter_parent_id,m.member_id,m.member_ww,m.member_qq,m.member_addtime,m.member_name,m.member_avatar,m.member_email,m.member_mobile,m.member_truename')->where('m.inviter_id IN'.$subQuery)->order('inviter_applytime desc')->paginate(['list_rows'=>10,'query' => request()->param()],false);
            $page_info=$res;
            $member_list=$res->items();
        }elseif($type==3){
            $subQuery=Db::name('member')->alias('m')->join('inviter i', 'i.inviter_id=m.member_id','LEFT')->field('m.member_id')->where('m.inviter_id='.$member_id)->order('inviter_applytime desc')->buildSql();
            $subQuery=Db::name('member')->alias('m')->join('inviter i', 'i.inviter_id=m.member_id','LEFT')->field('m.member_id')->where('m.inviter_id IN'.$subQuery)->order('inviter_applytime desc')->buildSql();
            $res=Db::name('member')->alias('m')->join('inviter i', 'i.inviter_id=m.member_id','LEFT')->field('i.*,m.inviter_id as inviter_parent_id,m.member_id,m.member_ww,m.member_qq,m.member_addtime,m.member_name,m.member_avatar,m.member_email,m.member_mobile,m.member_truename')->where('m.inviter_id IN'.$subQuery)->order('inviter_applytime desc')->paginate(['list_rows'=>10,'query' => request()->param()],false);
            $page_info=$res;
            $member_list=$res->items();
        }
        $inviterclass_model=model('inviterclass');
        foreach($member_list as $key => $item){
            $member_list[$key]['inviter_parent_name']='';
            $member_list[$key]['inviter_class']='';
            $member_list[$key]['inviter_class']=$inviterclass_model->getInviterclass(floatval($item['inviter_total_amount']));
            if($item['inviter_parent_id']){
                $member_list[$key]['inviter_parent_name'] = Db::name('member')->where('member_id='.$item['inviter_parent_id'])->value('member_name');
            }
        }
        View::assign('member_list',$member_list);
        View::assign('show_page', $page_info->render());
        echo View::fetch('memberlist');
    }
    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => lang('inviter_setting'),
                'url' => (string)url('Inviter/setting')
            ),
            array(
                'name' => 'goods',
                'text' => lang('inviter_goods'),
                'url' => (string)url('Inviter/goods')
            ),
            array(
                'name' => 'member',
                'text' => lang('inviter_member'),
                'url' => (string)url('Inviter/member')
            ),
            array(
                'name' => 'memberclass',
                'text' => lang('inviter_memberclass'),
                'url' => (string)url('Inviter/memberclass')
            ),
            array(
                'name' => 'order',
                'text' => lang('inviter_order'),
                'url' => (string)url('Inviter/order')
            ),
        );
        return $menu_array;
    }
}